<script setup>
//import {excelApi} from "../../../api/axios";
//import {MINIO_HOST} from "../../../const";
import {onMounted, reactive, ref, shallowReactive, shallowRef} from "vue";
import router from "../../../router";
import {
  dateFormat,
  myRemove,
  myPage,
  myRemoveBatch,
  getResponseData,
  clazzStatusFormat, elConfirm, isNotNull, myUpdate
} from "../../../util";
import {pageApi, removeApi, removeBatchApi, updateClazzMappingApi} from "../../../api/course.js";
import {listClazzNameApi, listInTrainingApi} from "../../../api/clazz.js";
import {listTeacherApi} from "../../../api/emp.js";
import {listApi as listStageApi} from "../../../api/stages.js";
import MyNav from "../../../components/MyNav.vue";
import MyHead from "../../../components/MyHead.vue";
import MyTable from "../../../components/MyTable.vue";
import MyPager from "../../../components/MyPager.vue";
import MyList from "../../../components/MyList.vue";

import {ElMessage, ElMessageBox} from 'element-plus'

/* ==================== 分页查询 ==================== */
// 表格数据 + 分页数据
let records = ref();
let pageInfo = shallowReactive({'pageNum': 1, 'pageSize': 5, 'fn': page});
// 分页查询条件字段：课程名称
let courseName = shallowRef();
let stageId = shallowRef();
let teacherId = shallowRef();
let status = shallowRef();

let dialogVisible = true

// 分页函数
async function page(pageNum = pageInfo['pageNum'], pageSize = pageInfo['pageSize']) {
  // 分页基础配置
  let config = {
    'api': pageApi,
    'params': {'pageNum': pageNum, 'pageSize': pageSize},
    'records': records,
    'pageInfo': pageInfo
  }

  // 附加为分页条件
  if (courseName.value) config['params']['name'] = courseName.value;
  if (teacherId.value) config['params']['teacherId'] = teacherId.value;
  if (stageId.value) config['params']['stageId'] = stageId.value;
  if (status.value !== null) config['params']['status'] = status.value;
  // 发送分页请求
  await myPage(config);
}

/* ==================== 查看详情 ==================== */
// 课程详情抽屉 + 课程详情列表数据
let detailDrawer = shallowRef();
let clazzMappingDrawer = shallowRef();
let detailItems = ref();


/* ==================== 查询全部的讲师记录 ==================== */
let teacherItems = [];

async function listTeacher() {
  let res = await listTeacherApi();
  let teachers = getResponseData(res);
  Object.values(teachers).forEach(item => {
    teacherItems.push({'label': item['name'], 'value': item['id']});
  });
}

/* ==================== 查询全部的授课阶段记录 ==================== */
let stageItems = [];

async function listStage() {
  let res = await listStageApi();
  let stages = getResponseData(res);
  Object.values(stages).forEach(item => {
    stageItems.push({'label': item['name'], 'value': item['id']});
  });
}

let statusItems = [
    {'label': '未开始', 'value': 0},
    {'label': '正在进行', 'value': 1},
    {'label': '已结束', 'value': 2}
];



async function listInTrainingClazz() {
  let res = await listInTrainingApi();
  let clazzes = getResponseData(res);
  Object.values(clazzes).forEach(item => {
    allClazzList.push(item);
    allClazzIds.push(item['id'])
  });
}

/**
 * 初始化课程详情抽屉
 * @param record
 */
function detail(record) {
  detailItems.value = [
    {'label': '课程名称', 'value': record['name']},
    {'label': '阶段', 'value': record['stageName']},
    {'label': '主讲老师', 'value': record['teacherName']},
    {'label': '开课时间', 'value': record['startTime'], 'format': dateFormat},
    {'label': '结课时间', 'value': record['endTime'], 'format': dateFormat},
    {'label': '状态', 'value': record['status'], format: courseStatusFormat, type: 'tag', tagTypeFn: status=>{
    if (status === 0 || status === '0') return 'warning';
    if (status === 1 || status === '1') return 'success';
    if (status === 2 || status === '2') return 'danger';
    return 'default';
  }},
    {'label': '创建时间', 'value': record['created'], 'format': dateFormat},
    {'label': '修改时间', 'value': record['updated'], 'format': dateFormat},
    {'label': '课程描述', 'value': record['info'], 'type': 'card'},
  ];
  detailDrawer.value = true;
}

/* ==================== 查询要完成本门课学习的班级名称 ==================== */
/*async function listClazzName(course) {
  let params = course.mapClazzIds.join(",")
  listClazzNameApi(params).then(res => {
    const data = getResponseData(res)

    for (let i in data) {
      course.mapClazzNameList.push(data[i])
    }
  })
}*/

let allClazzList = [], allClazzIds = [], allGradeList = [2020, 2021, 2022, 2023, 2024];
let clazzMapping = reactive({
  courseId: null,
  mapClazzList: [],
  mapGradeList: []
})

const checkAllClazz = ref(false)
const isClazzIndeterminate = ref(true)
const checkAllGrade = ref(false)
const isGradeIndeterminate = ref(true)

/**
 全【不】选班级复选框时执行
 */
const handleCheckAllClazzChange = (val) => {
  clazzMapping.mapClazzList = val ? allClazzIds : []
  isClazzIndeterminate.value = false
}
/**
 选择班级复选框时执行
 */
const handleCheckedClazzChange = (value) => {
  const checkedCount = value.length
  checkAllClazz.value = checkedCount === allClazzList.length
  // console.log("1：" + checkedCount)
  // console.log("2：" + allClazzList.length)
  isClazzIndeterminate.value = checkedCount > 0 && checkedCount < allClazzList.length
}
/**
 全【不】选年级复选框时执行
 */
const handleCheckAllGradeChange = (val) => {
  clazzMapping.mapGradeList = val ? allGradeList : []
  isGradeIndeterminate.value = false
}
/**
选择年级复选框时执行
 */
const handleCheckedGradeChange = (value) => {
  const checkedCount = value.length
  checkAllGrade.value = checkedCount === allGradeList.length
  isGradeIndeterminate.value = checkedCount > 0 && checkedCount < allGradeList.length
}

/**
 初始化设置课程-班级映射的抽屉
 */
function mapClazz(record) {
  clazzMapping.courseId = record['id']
  // console.log(record['mapClazzIds'])
  clazzMapping.mapClazzList = Array.from(record['mapClazzIds'])
  if (record['mapGradeList'] === 'ALL') {
    checkAllGrade.value = true
    clazzMapping.mapGradeList = Array.from(allGradeList)
  }
  else {
    clazzMapping.mapGradeList.splice(0)
    let arr = record['mapGradeList'].split(",")
    for (let i = 0; i < arr.length; i++) {
      clazzMapping.mapGradeList.push(parseInt(arr[i]))
    }
  }
  handleCheckedClazzChange(clazzMapping.mapClazzList)
  handleCheckedGradeChange(clazzMapping.mapGradeList)
  clazzMappingDrawer.value = true;
}

/* ==================== 设置授课班级 ==================== */
function updateClazzMapping() {
  const checkedClazzCount = clazzMapping.mapClazzList.length
  if (checkedClazzCount === 0) {
    return ElMessage.error("至少选择一个需要上课的班级")
  }
  const checkedGradeCount = clazzMapping.mapGradeList.length
  if (checkedGradeCount === 0) {
    return ElMessage.error("至少选择一个年级或全选")
  }


  let params = JSON.parse(JSON.stringify(clazzMapping));

  if (checkAllGrade.value === true) {
    params.mapGradeList.splice(0)
    params.mapGradeList.push("ALL")
  }
  // console.log(clazzMapping)
  updateClazzMappingApi(params).then(res => {
    const data = getResponseData(res)
    if (data) {
      ElMessage.success("设置成功");
      page()
    } else {
      ElMessage.error("程序出错了：" + data)
    }
  })
}
/* ==================== 单条添加 ==================== */
function insert() {
  router.push('/CourseInsert');
}

/* ==================== 单条修改 ==================== */
function update(row) {
  sessionStorage.setItem('course', JSON.stringify(row));
  router.push('/CourseUpdate');
}

/* ==================== 排课：安排上课日期和时间段 ==================== */
function scheduling(row) {
  sessionStorage.setItem('course', JSON.stringify(row));
  router.push('/Schedule');
}

/* ==================== 单条删除 ==================== */
function remove(row) {
  myRemove({'id': row['id'], 'api': removeApi, 'fn': page});
}

/* ==================== 批量删除 ==================== */
// 批量删除主键数组
let ids = [];

function selectionChange(rows) {
  ids = rows.map(e => e['id']);
}

function removeBatch() {
  myRemoveBatch({'ids': ids, 'api': removeBatchApi, 'fn': page})
}

/* ==================== 按课程名称模糊查询 ==================== */
function pageLikeName(val) {

  // 仅当输入框有值，或者当前处于按条件分页状态时，发送分页请求
  if (val || courseName.value) {
    courseName.value = val;
    page();
  }
}

/* ==================== 打印报表 ==================== */
function excel() {
  // excelApi('/clazz/excel', '课程统计表');
}

/* ==================== 按讲师查询 ==================== */
function pageByTeacherId(val) {
  // 仅当输入框有值，或者当前处于按条件分页状态时，发送分页请求
  if (val || teacherId.value) {
    teacherId.value = val;
    page();
  }
}
/* ==================== 按授课阶段查询 ==================== */
function pageByStageId(val) {
  // 仅当输入框有值，或者当前处于按条件分页状态时，发送分页请求
  if (val || stageId.value) {
    stageId.value = val;
    page();
  }
}

/* ==================== 按状态查询 ==================== */
function pageByStatus(val) {
  // 仅当输入框有值，或者当前处于按条件分页状态时，发送分页请求
  if (isNotNull(val) || isNotNull(status.value)) {
    status.value = val;
    page();
  }
}


/* ==================== 加载函数 ==================== */
onMounted(() => {
  page()
  listStage()
  listTeacher()
  listInTrainingClazz()
});

function handleDateChange(value) {
  // 处理日期选择变化
  console.log(value);
}

function courseStatusFormat(statusCode) {
  if (statusCode === '0' || statusCode === 0) return '未开始';
  if (statusCode === '1' || statusCode === 1) return '正在进行';
  if (statusCode === '2' || statusCode === 2) return '已结课';
  return '其他';
}

</script>

<template>

<my-nav :items="[
  {'icon': 'Avatar', 'label': '课程管理'},
  {'icon': 'User', 'label': '课程列表'},
]"/>

<my-head :items="[
  {'type': 'ipt', 'span': 5, 'placeholder': '按课程名称模糊搜索', 'fn': pageLikeName},
  {'type': 'opt', 'span': 5, 'placeholder': '按讲师搜索', 'fn': pageByTeacherId, 'optItems': teacherItems},
  {'type': 'opt', 'span': 5, 'placeholder': '按授课阶段搜索', 'fn': pageByStageId, 'optItems': stageItems},
  {'type': 'opt', 'span': 5, 'placeholder': '按课程状态搜索', 'fn': pageByStatus, 'optItems': statusItems},
  {'type': 'insertBtn', 'offset': 1, 'fn': insert},
  {'type': 'deleteBtn', 'fn': removeBatch},
  {'type': 'excelBtn', 'fn': excel},
]"/>

<my-table v-if="records" :records="records" :columns="[
  {'column': ['课程信息', '名称'], 'property': 'name', 'width': 200},
  {'column': ['课程信息', '阶段'], 'property': 'stageName', 'width': 120},
  {'column': ['课程信息', '讲师'], 'property': 'teacherName', 'width': 80},
  {'column': ['课程信息', '开课时间'], 'property': 'startTime', 'width': 120, 'format': dateFormat},
  {'column': ['课程信息', '结课时间'], 'property': 'endTime', 'width': 120, 'format': dateFormat},
  {'column': ['课程信息', '状态'], 'property': 'status', 'width': 120, format:courseStatusFormat, type: 'tag', 'tagTypeFn': status=>{
    if (status === 0 || status === '0') return 'warning';
    if (status === 1 || status === '1') return 'success';
    if (status === 2 || status === '2') return 'danger';
    return 'default';
  }},
  {'column': ['课程信息', '备注'], 'property': 'info', type: 'card'},
]" :buttons="[
  {'type': 'info', 'fn': detail},
  {'type': 'update', 'fn': update},
  {'btnLabel': '映射班级', 'btnType': 'warning', 'fn': mapClazz },
  {'btnLabel': '排课', 'btnType': 'warning', 'fn': scheduling },
  {'type': 'delete', 'fn': remove}
]" :selection-change="selectionChange"/>

<my-pager v-if="records" :page-info="pageInfo"/>

<el-drawer v-model="detailDrawer" size="30%">
  <my-list title="记录详情" :items="detailItems"/>
</el-drawer>

<el-drawer v-model="clazzMappingDrawer" size="30%">
  <template #default>
    <div>
      <h3>请选择需要上课的班级</h3>
      <el-checkbox v-model="checkAllClazz" :indeterminate="isClazzIndeterminate" @change="handleCheckAllClazzChange">
        全选
      </el-checkbox>
      <el-checkbox-group v-model="clazzMapping.mapClazzList" @change="handleCheckedClazzChange" size="large">
        <el-checkbox v-for="clazz in allClazzList" :key="clazz.id" :label="clazz.name" :value="clazz.id" size="large">
          {{ clazz.name }}
        </el-checkbox>
      </el-checkbox-group>

      <h3>请选择需要上课的学生年级</h3>
      <el-checkbox v-model="checkAllGrade" :indeterminate="isGradeIndeterminate" @change="handleCheckAllGradeChange">
        全选
      </el-checkbox>
      <el-checkbox-group v-model="clazzMapping.mapGradeList" @change="handleCheckedGradeChange" >
        <el-checkbox v-for="clazz in allGradeList" :key="clazz" :label="clazz" :value="clazz">
          {{ clazz }}
        </el-checkbox>
      </el-checkbox-group>

      <el-button type="primary" @click="updateClazzMapping">确认</el-button>
    </div>
  </template>
</el-drawer>


</template>

<style scoped lang="scss">

</style>